/*
 *  Copyright 2011.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.db.obj.vis.ui.actions;

import java.awt.event.ActionEvent;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.swing.KeyStroke;
import org.opu.db.obj.vis.ui.client.MainView;
import org.opu.db.obj.vis.ui.client.i18n.AbstractI18N;
import org.opu.db.obj.vis.ui.util.ConfigPath;
import org.opu.db.obj.vis.ui.util.Logger;
import org.opu.db.obj.vis.ui.util.Options;
import org.opu.db.obj.vis.ui.util.ResourceHandle;

/**
 *
 */
public abstract class AbstractAction extends javax.swing.AbstractAction{
	
	private static final long serialVersionUID = 7428109207584428711L;
	
	public static final String ACTIONLABELS = 
            "org.opu.db.obj.vis.ui.client.actions.ActionLabels";
    protected Logger logger = Logger.create(getClass());

    
    protected ResourceBundle boundle;
    protected Thread currentThread;
    /** set it true if action must be independent from other actions */
    protected boolean sequentially;// = false;
    private static AbstractAction currentAction;

    protected MainView mainView;
    private final String acionLabels;

    public AbstractAction() {
        this(false);
    }

    public AbstractAction(boolean sequentially) {
        this(sequentially, ACTIONLABELS);
    }

    public AbstractAction(String acionLabels) {
        this(false, acionLabels);
    }

    public AbstractAction(boolean sequentially, String acionLabels) {
        this.acionLabels = acionLabels;
        this.sequentially = sequentially;
        reset();
    }
    
    

    public void setMainView(MainView mainView) {
        this.mainView = mainView;
    }

    public final void reset(){
        setIcon();
        setText(ConfigPath.getInstance().getLocale());
    }

    protected void setIcon() {
        ResourceHandle.IconType small = ResourceHandle.IconType.small;
        ResourceHandle.IconType large = ResourceHandle.IconType.medium;
        putValue(SMALL_ICON, ResourceHandle.getIcon(getIconName(), small));
        putValue(LARGE_ICON_KEY, ResourceHandle.getIcon(getIconName(), large));
    }

    protected void setText(Locale locale) {
        boundle = AbstractI18N.getBundle(acionLabels, locale);
        safetyPutValue(NAME, getName());
        safetyPutValue(SHORT_DESCRIPTION, getName());
        safetyPutValue(LONG_DESCRIPTION, getName());

        // Set an accelerator key; this value is used by menu items
        String key = getSafety(getName() + "." + ACCELERATOR_KEY, "");
        if (!key.isEmpty()){
    		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(key));
        }

        // TODO: add mnemonic 
        // http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
        // putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_L));
    }
    
    public String getText(){
    	return String.valueOf(getValue(NAME));
    }

    protected void safetyPutValue(String name, String defVal){
        putValue(name, getSafety(getName() + "." + name, defVal));
    }

    protected String getSafety(String name, String defName){
        try {
            return boundle.getString(name);
        } catch (Exception e) {
            logger.error(getClass(), "Can't init property " + name);
            return defName;
        }
    }

    protected String getTextResource(String name){
        return boundle.getString(getName() + "." + name);
    }

    @Override
    public final void actionPerformed(ActionEvent e) {
        if (!sequentially && AbstractAction.currentAction != null){
            logger.warning("Action [" + getName() + "] can't be performed, action "
                    + "[" + currentAction.getName() + "] still processed.");
            return;
        }

        logger.info("Action [" + getName() + "] start");

        if (!sequentially) {
            AbstractAction.currentAction = this;
            mainView.strartAction(this);
        }

        try {
            action(e);
        } catch (Exception ex) {
            onFailure(ex);
            onActionFinish();
        }

        logger.info("Action [" + getName() + "] end");
    }

    public final void onActionFinish() {
        currentThread = null;
        if (!sequentially) {
            AbstractAction.currentAction = null;
            mainView.stopAction(this);
        }
    }

    public abstract String getName();

    /**
     * This method are called when action can be performed.
     * 
     * <B>NOTE:</B> IF YOU OVERWRITE THIS METHOD DON'T FORGET TO CALL 
     * {@link #onActionFinish()} AT THE END !
     */
    public void action(final ActionEvent e) throws Exception{
        currentThread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    logger.info("Start running");
                    runAction(e);
                    logger.info("Stop running");
                } catch (Exception ex) {
                    onFailure(ex);
                } finally {
                    onActionFinish();
                }
            }
        });
        currentThread.start();
    }

    /**
     * Overwrite this action if you want to work in assync mode.
     */
    public void runAction(ActionEvent e) throws Exception {
        // By default do nothing
    }

    protected void onFailure(Exception ex){
        logger.error(getClass(), ex);
        Options.error(ex);
    }

    public String getIconName(){
        return getName() + ".png";
    }

    public static String getText(String name){
        try {
            return AbstractI18N.getBundle(ACTIONLABELS,
                    ConfigPath.getInstance().getLocale()).getString(name);
        } catch (Exception e) {
            Logger.getInstance().error(AbstractAction.class,
                    "Can't init property " + name);
            return name;
        }
    }

    @SuppressWarnings("deprecation")
	public static void stopCurrentAction(){
        if (AbstractAction.currentAction != null){
            if (AbstractAction.currentAction.currentThread != null){
                AbstractAction.currentAction.currentThread.stop();
            }
            AbstractAction.currentAction.onActionFinish();
        }
    }
    
    protected String getDialogTitle() {
    	return getText() + " - " + ResourceHandle.getApplicationTitle(); 
    }
}
